# -*- coding: utf-8 -*-
"""
 ----------------------------------------
|File Name:     spider_and_check
|Author:        WYT
|date:          2020/8/5
 ----------------------------------------
|  Change Activity:
|                   2020/8/5:
-----------------------------------------
"""
from util.selenium.webdriver import Chrome
from util.selenium.webdriver.chrome.options import Options

from util.selenium.webdriver.common.by import By

from base.BaseMethod import BM
from settings import log_path
from spider_data.apps.parse_cover import parse_cover
from spider_data.apps.parse_hr import parse_hr
from spider_data.apps.parse_innoinfo import parse_innoinfo
from spider_data.apps.parse_ip import parse_ip
from spider_data.apps.parse_main_case import parseMainCase
from spider_data.apps.parse_ps import parse_ps
from spider_data.apps.parse_rd import parse_rd
from spider_data.apps.parse_rdcost import parse_rdcost
from spider_data.apps.parse_reg import parse_reg
from spider_data.apps.parse_sta import parse_sta
from spider_data.apps.parse_stand import parse_stand
from util.DataQuery.getFormData import getFormData
from util.Logger import Logger
from util.field_json import check_fields
from util.g import g
from util.inform.sendEmail import sendEmail


class SpiderCheck():

    def __init__(self, driver=None):
        self.driver = driver

    def check(self):
        try:
            if not g.db_values:
                g.put_db_values()
            print(g.db_values)
            for k, v in g.db_values.items():
                if type(v) == dict:
                    v_list = [__ for _, __ in v.items()]
                    if not all(v_list):
                        for key, values in v.items():
                            if not values:
                                g.db_values[k][key] = getFormData(name=key)
                else:
                    g.db_values[k] = getFormData(name=k)

            data_list = {
                'WriteApplicationCover': "parse_cover",
                'WriteRegistrationForm': "parse_reg",
                'WriteIPForm': "parse_ip",
                'WriteHrForm': "parse_hr",
                'WriteRDForm': "parse_rd",
                'WriteRdcostForm': "parse_rdcost",
                'WritePSForm': "parse_ps",
                'WriteMaincaseForm': "parseMainCase",
                'WriteInnovationAbilityForm': "parse_innoinfo",
                'IAStaDesc': "parse_sta",
                'WriteStandForm': "parse_stand"
            }
            iframe_loc = (By.NAME, "allrightiframe")
            main_frame_loc = (By.CSS_SELECTOR, 'frame#mainFrame')
            if not BM.isElementExist(element=(By.CSS_SELECTOR, ".contentIn"), driver=self.driver):
                if BM.isElementExist(element=iframe_loc, driver=self.driver):
                    BM.switch_to_frame(driver=self.driver, ele_loc=iframe_loc)
                if BM.isElementExist(element=main_frame_loc, driver=self.driver):
                    BM.switch_to_frame(driver=self.driver, ele_loc=main_frame_loc)
            for k, v in data_list.items():
                method = globals().get(v)
                g.logger.info("{}: {}".format(k, v))
                result = method(driver=self.driver)
                db_res = None
                if type(result) == bool or not result:
                    fl = result
                else:
                    key = result.get("key")
                    db_res = g.db_values.get(key)
                    if not db_res:
                        fl = True
                    else:
                        print("db_res: {}".format(db_res))
                        if key in db_res and len(db_res) == 1:
                            db_res = db_res.get(key)
                        remote_res = result.get("value")
                        print(remote_res)
                        # 对数据进行对比
                        fl = check_fields(remote_res=remote_res, db_res=db_res)
                print("{} fl: {}".format(k, fl))
                # if not fl and db_res is not None:
                #     a = sendEmail(subject="autoflow_{}".format("320000"), content="")
                #     a.content = "{} 对比不一致\n采集的数据: {} \n 数据库中的数据: {}".format(k, v, db_res)
                #     a.send_mail()
        except Exception as e:
            g.logger.error("error: {} file: {} line: {}".format(e, e.__traceback__.tb_frame.f_globals.get("__file__"),
                                                                e.__traceback__.tb_lineno))


if __name__ == '__main__':
    chrome_options = Options()
    chrome_options.add_experimental_option('debuggerAddress', '127.0.0.1:9222')
    chrome_options.add_argument('headless')
    driver = Chrome(chrome_options=chrome_options)

    logger = Logger(log_file_name=log_path + "spider_and_check.log",
                    log_level=Logger.INFO, logger_name='spider').get_log()

    g.logger = logger
    g.co_id = 188535
    g.year = 2020
    SpiderCheck(driver=driver).check()

